package com.lg.erp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.erp.entity.*;

import com.lg.erp.service.IMenuService;
import com.lg.erp.service.IRoleMenuService;
import com.lg.erp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ligen
 * @since 2021-04-12
 */
@RestController
public class FunctionsController {

    @Autowired
    private IMenuService functionsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleMenuService roleFunService;
    //获取对应用户名的权限展示
    @RequestMapping("/functions/username")
    public JsonResult getFunctionsByUsername(){
        //通过spring security的方法调用出用户的信息，注意这里的User使用的userDetails中的User不是实体类的user
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal instanceof User){
            User user=(User) principal;
            //按用户名查询菜单
            List<SMenu> functionsByUsername = functionsService.findFunctionsByUsername(user.getUsername());
            return new JsonResult(1,"ok",functionsByUsername);
        }
        else
            return new JsonResult(0,"badResult",null);
    }
    //获取所有权限
    @RequestMapping("/functions")
    public JsonResult getAllFunctions(){
        return new JsonResult(1,"ok",functionsService.findAllFunctions());
    }
    //获取所有用户对应的权限
    @RequestMapping("/functions/roles/{id}")
    public JsonResult findFunctionsByRoleId(@PathVariable("id") String id){
        List<SMenu> functionsByRoleId = functionsService.findFunctionsByRoleId(id);
        List ids=new ArrayList();
        for (SMenu functions : functionsByRoleId) {
            ids.add(functions.getId());
        }
        return new JsonResult(1,"ok",ids);
    }
    //权限展示页面进行展示
    @RequestMapping("/functions/{current}")
    public JsonResult findFunctionsByPage(@PathVariable Integer current){
        Page<SMenu> page=new Page<>(current,10);
        IPage<SMenu> pages=functionsService.getFunctionsByPage(page);
        return new JsonResult(1,"ok",pages);
    }
    //增加权限信息
    @RequestMapping(value ="/functions",method = RequestMethod.POST)
    public JsonResult saveFunction(@RequestBody SMenu functions){
        com.lg.erp.entity.SUser one = userService.getUserByLogin();
        functions.setId(UUID.randomUUID().toString().replace("-",""));
//            functions.setCreateUserId(one.getId().toString());
//            functions.setCreateTime(LocalDateTime.now());
            functionsService.save(functions);
        return new JsonResult(1,"添加权限成功",functions);
    }
    //更新权限信息
    @RequestMapping(value="/functions",method = RequestMethod.PUT)
    public JsonResult updateFunction(@RequestBody SMenu functions){
        SMenu fatherFun = functionsService.getOne(new QueryWrapper<SMenu>().lambda()
                .eq(SMenu::getId, functions.getMenuPid()));
        if (fatherFun==null||functions.getMenuPid().equals("0")){
            return new JsonResult(1,"更新权限失败父类不存在",null);
        }
        com.lg.erp.entity.SUser one = userService.getUserByLogin();
//        functions.setUpdateUserId(one.getId().toString());
//        functions.setUpdateTime(LocalDateTime.now());
        functionsService.updateById(functions);
        return new JsonResult(1,"更新权限成功",functions);
    }
    //删除权限信息
    @RequestMapping(value = "/functions/{id}",method = RequestMethod.DELETE)
    public JsonResult deleteFunction(@PathVariable String id){
        functionsService.removeById(id);
        roleFunService.remove(new QueryWrapper<SRoleMenu>().lambda()
                              .eq(SRoleMenu::getMenuId,id));
        List<SMenu> list = functionsService.list(new QueryWrapper<SMenu>()
                .lambda().eq(SMenu::getMenuPid, id));
        for (SMenu functions : list) {
            functionsService.removeById(functions.getId());
            roleFunService.remove(new QueryWrapper<SRoleMenu>().lambda()
                    .eq(SRoleMenu::getMenuId,functions.getId()));
        }
        return new JsonResult(1,"删除权限成功",null);
    }
    @RequestMapping(value = "fatherFunctions")
    public JsonResult getFatherFunctions(){
        List<SMenu> list = functionsService.list(new QueryWrapper<SMenu>().lambda()
                .eq(SMenu::getMenuPid, 0));
        return new JsonResult(1,"ok",list);
    }
}
